package com.xiaomage.view.draw12

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.view.View
import android.view.animation.LinearInterpolator

/**
 * Created by Administrator on 2018/1/9.
 */
class Xindiantuview(context: Context):View(context) {
    private val DSTBitmap=BitmapFactory.decodeResource(resources,
            R.drawable.xindiantu)
    private val SRCBitmap=Bitmap.createBitmap(
            DSTBitmap.width,
            DSTBitmap.height,
            Bitmap.Config.ARGB_8888
    )
    private val paint=getPaint()
    private var dx=0
    init {
        setLayerType(LAYER_TYPE_SOFTWARE,null)
        startAnimator()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawColor(Color.parseColor("#448ced"))
        val c=Canvas(SRCBitmap)
        c.drawColor(Color.BLACK,PorterDuff.Mode.CLEAR)
        c.drawRect(dx.toFloat(),
                0f,0f,
                DSTBitmap.height.toFloat(),paint)
        //canvas.drawBitmap(SRCBitmap,0f,0f,paint)
        //canvas.drawBitmap(DSTBitmap,0f,0f,paint)
        val layreId=canvas.saveLayer(0f,0f,width.toFloat(),
                height.toFloat(),null,Canvas.ALL_SAVE_FLAG)
        canvas.drawBitmap(DSTBitmap,0f,0f,paint)
        paint.setXfermode(PorterDuffXfermode(PorterDuff.Mode.DST_OUT))
        canvas.drawBitmap(SRCBitmap,0f,0f,paint)
        paint.xfermode=null
        canvas.restoreToCount(layreId)
    }
    private fun startAnimator(){
        val valueAnimator=ValueAnimator.ofInt(DSTBitmap.width,0)
        valueAnimator.duration=9000
        valueAnimator.repeatCount=ValueAnimator.INFINITE
        valueAnimator.repeatMode=ValueAnimator.RESTART
        valueAnimator.interpolator=LinearInterpolator()
        valueAnimator.addUpdateListener {
            animator->
            dx=animator.animatedValue.toString().toInt()
            postInvalidate()
        }
        valueAnimator.start()
    }

    private fun getPaint(): Paint {
        val paint= Paint()
        paint.isAntiAlias=true
        paint.color= Color.GREEN
        paint.style= Paint.Style.FILL_AND_STROKE
        return paint
    }

}